package com.dictionary.hi;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;
import com.inapp.util.BillingService;
import com.mango9x.utils.HttpHelpers;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ViewAnimator;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class CategoriesViewController extends AbstractViewController {

	private MainTabHostActivity mainTabHostActivity;
	private View v;
	private ViewAnimator mainViewAnimator;
	private ListView listView;
	private TextView messageView;
	private DisplayImageOptions options;
	private ImageAdapter imageAdapter;

	private List<Category> categories = new ArrayList<CategoriesViewController.Category>();

	public CategoriesViewController(AbstractTabRootManager tabRootManager,
			Bundle args) {
		super(tabRootManager, R.layout.vc_categories);
		try {
			mainTabHostActivity = (MainTabHostActivity) getActivity();
			v = getView();
			mainViewAnimator = (ViewAnimator) v
					.findViewById(R.id.main_view_flipper);
			listView = (ListView) v.findViewById(R.id.list_view);
			messageView = (TextView) v
					.findViewById(R.id.progress_message_text_view);
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.loading)
					.showImageForEmptyUri(R.drawable.ic_launcher)
					.displayer(new BitmapDisplayer() {

						public Bitmap display(Bitmap bitmap, ImageView imageView) {
							imageView.setAnimation(AnimationUtils
									.loadAnimation(mainTabHostActivity,
											R.anim.fade_in));
							imageView.setImageBitmap(bitmap);
							return bitmap;
						}
					}).cacheInMemory().cacheOnDisc().build();
			downloadandShowData();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void loadData() {

		try {

			boolean isProVersion = BillingService.isPurchased(
					getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
					|| mainTabHostActivity.getPackageName().endsWith("pro");
			String url = isProVersion ? getString(R.string.category_list_url_pro)
					: getString(R.string.category_list_url);
			
			JSONObject json = HttpHelpers.getJSONfromURL(url);

			JSONArray jCategoruies = json.getJSONArray("categories");
			categories.clear();
			for (int i = 0; i < jCategoruies.length(); i++) {
				JSONArray jCategory = jCategoruies.getJSONArray(i);
				Category category = new Category();
				category.id = jCategory.getInt(0);
				category.name = jCategory.getString(1);
				category.catImage = jCategory.getString(2);
				category.description = jCategory.getString(3);
				categories.add(category);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void downloadandShowData() {
		new AsyncTask<String, String, String>() {
			protected void onPreExecute() {
				try {
					messageView.setText(R.string.loading);
					mainViewAnimator.setDisplayedChild(0);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					loadData();

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {

					imageAdapter = new ImageAdapter(getActivity());
					listView.setAdapter(imageAdapter);
					listView.setOnItemClickListener(new OnItemClickListener() {

						public void onItemClick(AdapterView<?> arg0, View arg1,
								int position, long arg3) {
							try {
								Bundle bundle = new Bundle();
								Category category = categories.get(position);
								boolean isProVersion = BillingService.isPurchased(
										getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
										|| mainTabHostActivity.getPackageName().endsWith("pro");
								String url = isProVersion ? getString(R.string.category_images_url_pro)
										: getString(R.string.category_images_url);
								
								bundle.putString(
										ShowCategoryViewController.KEY_CATEGORY_URL,
										url + category.id);
								bundle.putInt(
										ShowCategoryViewController.KEY_LOAD_TYPE,
										ShowCategoryViewController.LOAD_TYPE_URL);
								pushViewController(new ShowCategoryViewController(
										getTabRootManager(), bundle));
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
					mainViewAnimator.setDisplayedChild(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	public class ImageAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public ImageAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return categories.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			try {
				if (convertView == null) {
					convertView = mInflater.inflate(
							R.layout.category_list_content, null);
					holder = new ViewHolder();
					holder.imageView = (ImageView) convertView
							.findViewById(R.id.image);
					holder.title = (TextView) convertView
							.findViewById(R.id.lable);
					holder.desc = (TextView) convertView
							.findViewById(R.id.desc);
					convertView.setTag(holder);

				} else {
					holder = (ViewHolder) convertView.getTag();
				}

				holder.title.setText(categories.get(position).name);
				holder.desc.setText(categories.get(position).description);
				mainTabHostActivity.getImageLoader().displayImage(
						categories.get(position).catImage, holder.imageView,
						options);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			ImageView imageView;
			TextView title;
			TextView desc;
		}
	}

	class Category {
		private int id;
		private String name;
		private String catImage;
		private String description;
	}
}
